import React, { useState } from 'react';
import { Table } from 'antd';
import cls from 'classnames';
import '@/common/pageLayout.less';
import { departmentAPI } from '@/pages/SystemController/DepartmentController/type';

export const TableList = React.forwardRef(
  (
    { dataSource, columns, loading, expandIcon }: departmentAPI.ITableLIst,
    ref: any,
  ) => {
    const [expandedRowKeys, setExpand] = useState([]);
    const [openSearchKey, setOpenSearchKey] = useState<any>([]); //保存选中项 的key
    const [openSearchRow, setOpenSearchRow] = useState<any>([]); //保存选中项的数据

    React.useImperativeHandle(ref, () => ({
      setExpandedKeys: (expands: any) => {
        onExpandedRowsChange(expands);
      },
      setTableChanage: (tableKey: any, tableRow: any) => {
        tableChange(tableKey, tableRow);
      },
      openSearchKey: openSearchKey,
      openSearchRow: openSearchRow,
    }));

    let showColumns = React.useMemo(() => {
      let newColumns: any = [];

      columns.forEach((i) => {
        if (i?.visible) {
          newColumns.push(i);
        }
      });

      return newColumns;
    }, [columns]);

    const onExpandedRowsChange = (expands: any) => {
      if (expands) {
        setExpand(expands);
      }
    };
    // 表格选中项变化
    const tableChange = (selectedRowKeys: any, selectedRows: any) => {
      if (typeof selectedRowKeys == 'string') {
        let newSelectKeys = [selectedRowKeys];
        setOpenSearchKey(newSelectKeys);
        setOpenSearchRow(selectedRows);
      } else {
        setOpenSearchKey(selectedRowKeys);
        setOpenSearchRow(selectedRows);
      }
    };
    return (
      <div className={cls('list-table')}>
        <Table
          columns={showColumns}
          loading={loading}
          dataSource={dataSource}
          rowKey={(record) => record?.id}
          expandedRowKeys={expandedRowKeys}
          size="small"
          bordered
          pagination={false}
          scroll={{ x: 1200, y: 'true' }}
          onExpandedRowsChange={onExpandedRowsChange}
          rowSelection={{
            type: 'radio',
            // selectedRowKeys: ['1000000000000001'],
            selectedRowKeys: openSearchKey,
            onChange: tableChange,
          }}
          // expandIcon={expandIcon}
          expandable={{
            expandIcon: expandIcon
          }}
          onRow={(record) => {
            return {
              onClick: (event) => {
                event.stopPropagation();
                tableChange(record?.id, record);
              },
            };
          }}
        />
      </div>
    );
  },
);
